<template>
	<view class="asset-list-container">

		<!-- 选择模式下的操作栏 -->
		<view class="select-bar" v-if="selectMode">
			<text class="select-info">已选择 {{ selectedAssets.length }} 个资产</text>
			<view class="select-actions">
				<text class="action-btn" @click="clearSelection">清空</text>
				<text class="action-btn confirm" @click="confirmSelection">确定</text>
			</view>
		</view>

		<view class="search-row">
			<view class="search-box">
				<text class="search-icon">🔍</text>
				<input class="search-input" v-model="keyword" placeholder="资产编号、设备名称" @input="onKeywordInput" @confirm="doSearch" />
			</view>
			<text class="icon-btn" @click="openScan">📷</text>
			<text class="icon-btn" @click="openSort">⇅</text>
			<text class="icon-btn" @click="openFilter">⋯️</text>
		</view>

		<!-- 顶部分类tab -->
		<scroll-view class="tabs" scroll-x>
			<view v-for="t in tabs" :key="t.key" :class="['tab', currentTab===t.key ? 'active' : '']" @click="switchTab(t.key)">{{ t.name }}</view>
		</scroll-view>

		<!-- 列表（简洁卡片样式） -->
		<view class="asset-list">
			<view class="asset-item" v-for="(item, idx) in filteredList" :key="item.id" @click="goDetail(item)" :class="{ 'selected': isSelected(item) }">
				<!-- 选择模式下的选择框 -->
				<view class="select-checkbox" v-if="selectMode" @click.stop="toggleSelection(item)">
					<text class="checkbox-icon" :class="{ 'checked': isSelected(item) }">{{ isSelected(item) ? '✓' : '' }}</text>
				</view>
				<image class="asset-image" :src="item.image || '../../static/banner-bg.jpg'" mode="aspectFill"></image>
				<view class="asset-info">
					<text class="asset-name">{{ item.name }}</text>
					<text class="asset-detail">资产编号：{{ item.assetNo }}</text>
					<text class="asset-detail">设备位置：{{ item.location }}</text>
					<text class="asset-detail">设备状态：<text :class="['status', item.status]">{{ item.statusText }}</text></text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import assetApi from '@/api/asset/asset.js'
import { listDeviceType } from '@/api/dict/deviceType.js'
import { getDicts } from '@/api/dict/data.js'
export default {
		data() {
			return {
				keyword: '',
				currentTab: 'all',
				mode: '', // 模式：edit-编辑模式，delete-删除模式，空字符串-查看模式
				selectMode: false, // 选择模式：用于备件添加时选择关联资产
				selectedAssets: [], // 已选择的资产
				// 元数据与筛选
				deviceTypes: [],
				statusList: [],
				selectedType: '',
				selectedStatus: '',
				selectedTypeName: '',
				selectedStatusName: '',
				sortKey: '', // name|status|createdTime 等后端支持的字段
				sortOrder: 'asc',
				debounceTimer: null,
				tabs: [
					{ key: 'all', name: '全部设备' },
					{ key: 'ASSET_STATUS_001', name: '正常' },
					{ key: 'ASSET_STATUS_002', name: '故障中' },
					{ key: 'ASSET_STATUS_003', name: '闲置中' },
					{ key: 'ASSET_STATUS_004', name: '已报废' }
				],
				list: []
			}
		},
		onLoad(options) {
			this.mode = options.mode || '';
			this.selectMode = options.selectMode === 'true';
			this.loadMeta().then(() => this.fetchList());
		},
		computed: {
			pageTitle(){
				if(this.selectMode) return '选择资产'
				if(this.mode==='edit') return '资产编辑'
				if(this.mode==='delete') return '资产删除'
				return '资产管理'
			},
			sortLabel() {
				if (!this.sortKey) return ''
				const map = { name: '名称', status: '状态', createdTime: '创建时间' }
				const order = this.sortOrder === 'desc' ? '↓' : '↑'
				return `${map[this.sortKey] || this.sortKey}${order}`
			},
			filteredList() {
				return this.list
					.filter(i => {
						// 如果是"全部设备"，显示所有
						if (this.currentTab === 'all') return true;
						
						// 否则根据状态过滤
						const itemStatus = i.status || i.statusCode;
						return itemStatus === this.currentTab;
					})
					.filter(i => !this.keyword || (i.name + i.assetNo).toLowerCase().includes(this.keyword.toLowerCase()));
			}
		},
		methods: {
			async loadMeta(){
				try {
					const r1 = await listDeviceType({})
					const rows = r1.rows || r1.data || []
					this.deviceTypes = rows.map(x => ({ code: x.code || x.id || '', name: x.name || x.typeName || '' }))
				} catch(e) {}
				try {
					const r2 = await getDicts('asset_status')
					const arr = r2.data || r2 || []
					this.statusList = arr.map(d => ({ code: d.dictValue, name: d.dictLabel }))
				} catch(e) {}
			},
			onKeywordInput(){
				clearTimeout(this.debounceTimer)
				this.debounceTimer = setTimeout(() => this.fetchList(), 400)
			},
			switchTab(key) { 
				console.log('切换分类标签:', key);
				this.currentTab = key; 
				this.fetchList(); 
			},
			doSearch() { this.fetchList() },
			openScan() { uni.showToast({ title: '扫描开发中', icon: 'none' }); },
			openSort() {
				const items = ['按名称升序','按名称降序','按状态升序','按状态降序','清除排序']
				uni.showActionSheet({
					itemList: items,
					success: ({ tapIndex }) => {
						if (tapIndex === 4){ this.sortKey=''; this.fetchList(); return }
						const map = [ ['name','asc'], ['name','desc'], ['status','asc'], ['status','desc'] ]
						[this.sortKey, this.sortOrder] = map[tapIndex]
						this.fetchList()
					}
				})
			},
			openFilter() {
				const items = ['选择设备类型','添加资产','删除资产','更新状态']
				uni.showActionSheet({
					itemList: items,
					success: ({ tapIndex }) => {
						if (tapIndex === 0) this.chooseType()
						else if (tapIndex === 1) this.goToAddAsset()
						else if (tapIndex === 2) this.switchToDeleteMode()
						else if (tapIndex === 3) this.switchToStatusUpdateMode()
					}
				})
			},
			switchToDeleteMode() {
				// 切换到删除模式
				this.mode = 'delete';
				uni.showToast({
					title: '已进入删除模式，点击资产进行删除',
					icon: 'none'
				});
			},
			
			switchToStatusUpdateMode() {
				// 切换到状态更新模式
				this.mode = 'status';
				uni.showToast({
					title: '已进入状态更新模式，点击资产进行状态更新',
					icon: 'none'
				});
			},
			goToAddAsset() {
				uni.navigateTo({ url: '/pages/asset/add' })
			},
			chooseType(){
				const names = this.deviceTypes.map(d => d.name)
				uni.showActionSheet({ itemList: names, success: ({ tapIndex }) => {
					const it = this.deviceTypes[tapIndex]
					this.selectedType = it?.code || ''
					this.selectedTypeName = it?.name || ''
					this.fetchList()
				}})
			},
			chooseStatus(){
				const names = this.statusList.map(s => s.name)
				uni.showActionSheet({ itemList: names, success: ({ tapIndex }) => {
					const it = this.statusList[tapIndex]
					this.selectedStatus = it?.code || ''
					this.selectedStatusName = it?.name || ''
					this.fetchList()
				}})
			},
			clearFilters(){
				this.selectedType = ''
				this.selectedStatus = ''
				this.selectedTypeName = ''
				this.selectedStatusName = ''
				this.fetchList()
			},
            goDetail(item) {
                const assetNo = item.assetNo || item.id || item.code;
                console.log('点击资产项目:', item, 'assetNo:', assetNo, 'mode:', this.mode, 'selectMode:', this.selectMode);
                
                if (this.selectMode) {
                    // 选择模式：切换选择状态
                    this.toggleSelection(item);
                } else if (this.mode === 'edit') {
                    // 编辑模式：跳转到编辑页面
                    console.log('跳转到编辑页面，URL:', `/pages/asset/edit?assetNo=${assetNo}`);
                    uni.navigateTo({ url: `/pages/asset/edit?assetNo=${assetNo}` });
                } else if (this.mode === 'delete') {
                    // 删除模式：显示确认删除对话框
                    this.confirmDelete(item);
                } else if (this.mode === 'status') {
                    // 状态更新模式：显示状态选择对话框
                    this.showStatusUpdateDialog(item);
                } else {
                    // 查看模式：跳转到详情页面
                    uni.navigateTo({ url: `/pages/asset/detail?assetNo=${assetNo}` });
                }
			},
			goBack() { uni.navigateBack({ delta: 1 }); },

            // 确认删除资产
            async confirmDelete(item) {
                const assetNo = item.assetNo || item.id || item.code;
                const assetName = item.name || item.assetName || '该资产';

                uni.showModal({
                    title: '确认删除',
                    content: `确定要删除资产"${assetName}"吗？此操作不可撤销。`,
                    success: async (res) => {
                        if (res.confirm) {
                            try {
                                await assetApi.delAsset(assetNo);
                                uni.showToast({ title: '删除成功', icon: 'success' });
                                // 重新加载列表
                                this.fetchList();
                            } catch (e) {
                                console.error('删除资产失败', e);
                                uni.showToast({ title: '删除失败', icon: 'none' });
                            }
                        }
                    }
                });
            },

            // 显示状态更新对话框
            showStatusUpdateDialog(item) {
                const assetName = item.name || item.assetName || '该资产';
                const currentStatus = item.status || item.statusCode;
                
                // 根据当前状态显示可选的下一状态
                const statusOptions = this.getAvailableStatusOptions(currentStatus);
                
                if (statusOptions.length === 0) {
                    uni.showToast({
                        title: '当前状态无法更新',
                        icon: 'none'
                    });
                    return;
                }

                uni.showActionSheet({
                    title: `更新资产"${assetName}"状态`,
                    itemList: statusOptions.map(opt => opt.name),
                    success: async (res) => {
                        const selectedOption = statusOptions[res.tapIndex];
                        await this.updateAssetStatus(item, selectedOption.code, selectedOption.name);
                    }
                });
            },

            // 获取可用的状态选项
            async getAvailableStatusOptions(currentStatus) {
                try {
                    // 从字典表加载资产状态
                    const res = await uni.request({
                        url: 'http://127.0.0.1:8081/system/status/asset/list',
                        method: 'GET',
                        header: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${uni.getStorageSync('token')}`
                        },
                        data: {
                            pageNum: 1,
                            pageSize: 9999,
                            enabled: 1
                        }
                    });
                    
                    const allStatuses = (res.data?.data || []).map(item => ({
                        code: item.code,
                        name: item.name
                    }));
                    
                    // 如果API调用失败，使用兜底数据
                    if (allStatuses.length === 0) {
                        return this.getFallbackStatusOptions(currentStatus);
                    }
                    
                    // 根据当前状态过滤可用选项
                    if (currentStatus === 'ASSET_STATUS_001') { // 正常
                        return allStatuses.filter(s => s.code !== 'ASSET_STATUS_001');
                    } else if (currentStatus === 'ASSET_STATUS_002') { // 故障
                        return allStatuses.filter(s => s.code !== 'ASSET_STATUS_002');
                    } else if (currentStatus === 'ASSET_STATUS_003') { // 闲置
                        return allStatuses.filter(s => s.code !== 'ASSET_STATUS_003');
                    } else if (currentStatus === 'ASSET_STATUS_004') { // 报废
                        return []; // 报废状态不能转换
                    }
                    
                    return allStatuses; // 默认返回所有选项
                } catch (error) {
                    console.error('加载资产状态失败:', error);
                    return this.getFallbackStatusOptions(currentStatus);
                }
            },
            
            // 兜底状态选项
            getFallbackStatusOptions(currentStatus) {
                const allStatuses = [
                    { code: 'ASSET_STATUS_001', name: '正常' },
                    { code: 'ASSET_STATUS_002', name: '故障' },
                    { code: 'ASSET_STATUS_003', name: '闲置' },
                    { code: 'ASSET_STATUS_004', name: '报废' }
                ];

                // 根据当前状态过滤可用选项
                if (currentStatus === 'ASSET_STATUS_001') { // 正常
                    return allStatuses.filter(s => s.code !== 'ASSET_STATUS_001');
                } else if (currentStatus === 'ASSET_STATUS_002') { // 故障
                    return allStatuses.filter(s => s.code !== 'ASSET_STATUS_002');
                } else if (currentStatus === 'ASSET_STATUS_003') { // 闲置
                    return allStatuses.filter(s => s.code !== 'ASSET_STATUS_003');
                } else if (currentStatus === 'ASSET_STATUS_004') { // 报废
                    return []; // 报废状态不能转换
                }
                
                return allStatuses; // 默认返回所有选项
            },

            // 更新资产状态
            async updateAssetStatus(item, newStatusCode, newStatusName) {
                const assetNo = item.assetNo || item.id || item.code;
                const assetName = item.name || item.assetName || '该资产';
                
                try {
                    uni.showLoading({ title: '更新中...' });
                    
                    await assetApi.updateAssetStatus(assetNo, newStatusCode);
                    
                    uni.hideLoading();
                    uni.showToast({
                        title: `状态已更新为${newStatusName}`,
                        icon: 'success'
                    });
                    
                    // 重新加载列表
                    this.fetchList();
                } catch (e) {
                    uni.hideLoading();
                    console.error('更新资产状态失败', e);
                    uni.showToast({
                        title: e.message || '更新失败',
                        icon: 'none'
                    });
                }
            },

			// 选择模式相关方法
			toggleSelection(item) {
				const index = this.selectedAssets.findIndex(asset => asset.assetNo === item.assetNo);
				if (index > -1) {
					// 已选择，取消选择
					this.selectedAssets.splice(index, 1);
				} else {
					// 未选择，添加到选择列表
					this.selectedAssets.push({
						assetNo: item.assetNo,
						assetName: item.name,
						location: item.location,
						status: item.status
					});
				}
			},

			isSelected(item) {
				return this.selectedAssets.some(asset => asset.assetNo === item.assetNo);
			},

			clearSelection() {
				this.selectedAssets = [];
			},

			confirmSelection() {
				if (this.selectedAssets.length === 0) {
					uni.showToast({ title: '请选择至少一个资产', icon: 'none' });
					return;
				}
				// 将选中的资产存储到本地存储
				uni.setStorageSync('selectedAssets', this.selectedAssets);
				// 返回上一页
				uni.navigateBack();
			},

			// 拉取真实数据
      async fetchList() {
				try {
					const query = {};
					// 按tab映射状态
					if (this.currentTab !== 'all') {
						query.statusCode = this.currentTab; // 使用正确的状态编码字段
					}
					if (this.keyword) query.keyword = this.keyword;
					if (this.selectedType) query.typeCode = this.selectedType;
					if (this.selectedStatus) query.statusCode = this.selectedStatus;
					if (this.sortKey) { query.orderByColumn = this.sortKey; query.isAsc = this.sortOrder; }
					const res = await assetApi.listAsset(query);
					const rows = res.rows || res.data || res || [];
          this.list = rows.map((r, idx) => {
					const statusMap = {
						'ASSET_STATUS_001': { text: '正常', cls: 'ok' },
						'ASSET_STATUS_002': { text: '故障', cls: 'fault' },
						'ASSET_STATUS_003': { text: '闲置', cls: 'idle' },
						'ASSET_STATUS_004': { text: '报废', cls: 'reported' },
						// 兼容旧的状态值
						'ok': { text: '正常', cls: 'ok' },
						'fault': { text: '故障', cls: 'fault' },
						'idle': { text: '闲置中', cls: 'idle' },
						'maintain': { text: '待保养', cls: 'pending' },
						'inspect': { text: '待点检', cls: 'inspect' },
						'reported': { text: '已报废', cls: 'reported' },
						'pending': { text: '待保养', cls: 'pending' }
					};
						const statusKey = r.status || r.statusCode || 'ASSET_STATUS_001';
						const m = statusMap[statusKey] || statusMap['ASSET_STATUS_001'];
                        // 构造封面缩略图（优先取第一张）
                        const firstImage = (() => {
                            const minioBase = uni.getStorageSync('MINIO_BASE') || 'https://io.brightholdings.cn';
                            const bucket = 'smart-maintenance';
                            const imgs = Array.isArray(r.imageUrls) ? r.imageUrls : (typeof r.imageUrls === 'string' ? r.imageUrls.replace(/[\[\]"]+/g,'').split(',') : []);
                            const name = (imgs[0] || '').trim();
                            if (!name) return '/static/banner-bg.jpg';
                            if (/^https?:\/\//i.test(name)) return name;
                            // 使用MinIO方式构建图片URL
                            return `${minioBase.replace(/\/$/, '')}/${bucket}/${name}`;
                        })();
                        return {
							id: r.id || idx,
							name: r.assetName || r.deviceName || r.name || '-',
							assetNo: r.assetNo || r.code || '-',
							location: r.location || r.assetLocation || '-',
							status: statusKey,
							statusText: m.text,
							statusClass: m.cls,
                            image: firstImage
						};
          });
				} catch (e) {
					console.error('获取资产列表失败', e);
					uni.showToast({ title: '获取资产列表失败', icon: 'none' });
				}
			}
		}
	}
</script>
<style>
/* 资产列表容器 */
.asset-list-container {
  min-height: 100vh;
  background: #ffffff;
  padding-bottom: 120rpx;
}

/* 标题样式 */
.title {
  font-size: 36rpx;
  font-weight: 700;
}

/* 搜索栏样式 */
.search-row {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 16rpx 20rpx;
  background: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f1f2f6;
  border-radius: 28rpx;
  padding: 12rpx 20rpx;
}

.search-icon {
  margin-right: 12rpx;
  color: #999;
}

.search-input {
  flex: 1;
  font-size: 26rpx;
}

.icon-btn {
  width: 60rpx;
  text-align: center;
  font-size: 30rpx;
}

/* 标签栏样式 */
.tabs {
  white-space: nowrap;
  background: #ffffff;
  padding: 10rpx 12rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.tab {
  display: inline-block;
  padding: 12rpx 20rpx;
  margin-right: 12rpx;
  border-radius: 32rpx;
  background: #f1f2f6;
  color: #666;
  font-size: 24rpx;
  font-weight: 700;
}

.tab.active {
  background: #e7f0ff;
  color: #007aff;
  font-weight: 700;
}

/* 列表样式 */
.asset-list {
  padding: 0;
}

.asset-item {
  width: 100%;
  margin-bottom: 20rpx;
  position: relative;
  overflow: hidden;
  border-radius: 0;
  display: flex;
  background: #ffffff;
}

.asset-image {
  width: 200rpx;
  height: 200rpx;
  flex-shrink: 0;
  background-color: #f5f5f5;
}

.asset-info {
  padding: 20rpx 24rpx;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.asset-name {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 12rpx;
  color: #333;
}

.asset-detail {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin: 4rpx 0;
  line-height: 1.5;
}

/* 状态样式 */
.status {
  font-weight: 600;
}

.status.ok, .status.normal {
  color: #21c25e;
}

.status.fault, .status.error {
  color: #ff4d4f;
}

.status.reported, .status.scrapped {
  color: #999;
}

.status.pending, .status.maintenance, .status.inspection {
  color: #ff9800;
}

.status.idle {
  color: #007aff;
}

/* 选择模式样式 */
.select-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 24rpx;
  background: #f0f8ff;
  border-bottom: 1rpx solid #e0e0e0;
}

.select-info {
  font-size: 28rpx;
  color: #007aff;
  font-weight: 500;
}

.select-actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 24rpx;
  background: #fff;
  color: #666;
  border: 1rpx solid #ddd;
}

.action-btn.confirm {
  background: #007aff;
  color: #fff;
  border-color: #007aff;
}

.asset-item.selected {
  border: 2rpx solid #007aff;
}

.select-checkbox {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  z-index: 10;
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background: rgba(0, 122, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox-icon {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  border: 2rpx solid #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #fff;
  background: transparent;
}

.checkbox-icon.checked {
  background: #fff;
  color: #007aff;
}
</style>

